<?php
/**
 * 百度百科
 */
if (empty($regex_matches['s'])) {
    return;
}
$word = trim($regex_matches['s']);
if (mb_strlen($word, 'UTF-8') > 8) {
    return;
}
$url = 'https://wapbaike.baidu.com/searchresult?word=%s';
$url = sprintf($url, $word);
$resp = curl_http_request($url);
// 调试日志
//file_put_contents(runtime_path() . '/userApi_baike.log', __METHOD__ . PP($resp['response'], false));
if (isset($resp['status']['http_code']) && (200 == $resp['status']['http_code']) && !empty($resp['response'])) {
    preg_match('|<ul.*id="searchList">.*</ul>|isU', $resp['response'], $content);
    if (!empty($content[0])) {
        $content = preg_replace('/(<em>|<em.*>|<\/em>)/', '', $content[0]);
        if (preg_match_all('|<li>.*<a href="(?<link>.+)">.*<span>(?<title>.+) - 百度百科</span>.*<p>(?<description>.+)</p>.*</a>.*</li>|isU', $content, $matchs)) {
            $ds = array();
            foreach ($matchs['title'] as $key => $v) {
                $ds[] = array(
                    'title' => strip_tags($v),
                    'link' => $matchs['link'][$key],
                    'description' => strip_tags($matchs['description'][$key]),
                );
            }
            $news = array();
            if (!preg_match('/^http(s)?:\\/\\/.+/', $ds[0]['link'])) {
                $ds[0]['link'] = 'https://baike.baidu.com' . $ds[0]['link'];
            }
            $news[] = array('title' => "{$word} 的百科解释如下", 'description' => $ds[0]['description'], 'picurl' => 'http://g.hiphotos.baidu.com/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=f38225303901213fdb3e468e358e5db4/9358d109b3de9c82afcae8666c81800a18d8bc3eb0356b97.jpg', 'url' => $ds[0]['link']);
            $cnt = min(count($ds), 8);
            for ($i = 0; $i < $cnt; ++$i) {
                $news[] = array(
                    'title' => $ds[$i]['title'],
                    'description' => $ds[$i]['description'],
                    'picurl' => '',
                    'url' => $ds[$i]['link'],
                );
            }

            echo build_baike_response($news);
        }
    }
}

function build_baike_response($news = []): string
{
    $data = '';
    $row = array_shift($news);
    //foreach ($news as $row) {
    $data .= $row['title'] . PHP_EOL .
        $row['description'] . PHP_EOL .
        $row['url'] . PHP_EOL;
    //}
    return $data;
}
